function buildChat() {
    var chatWin = $("<div/>",{
        id:"chatwindow",
        css:{
            borderRadius: "10px",
            border: "1px solid black",
            position: "fixed",
            bottom: -200,
            height:200,
            width:240,
            marginLeft:4,
            padding:10,
            backgroundColor:"white",
            right:0
        }
    }).appendTo(document.body).animate({
        bottom: -180
    });

    var label = $("<span/>",{
    }).addClass("chatnamefields").appendTo(chatWin).text("Name: ");

    var value = $("<input/>",{
            type:'text',
            id:'chatname',
            css: {
                width:110
            }
    }).addClass("chatnamefields").appendTo(chatWin);

    var button = $("<button/>",{
    }).addClass("chatnamefields").appendTo(chatWin).text("Start Chat").click(startChat);

    if ( localStorage && localStorage["chatname"] && localStorage.chatname != "" ) {
        value.val(localStorage.chatname);
        setTimeout(startChat,30);
    }

    var texts = $("<div/>",{
        id: "texts",
        css: {
            border: "1px solid black",
            borderRadius: 0,
            padding: 5,
            height:165,
            overflow:"hidden",
            opacity: 0
        }
    }).addClass("chatfields").appendTo(chatWin);

    var label = $("<span/>",{
    }).addClass("chatfields").appendTo(chatWin).text("Say: ");

    var value = $("<input/>",{
            type:'text',
            id:'chat',
            css: {
                width:110
            }
    }).addClass("chatfields").appendTo(chatWin);

    var msg = $("<div/>",{
    }).appendTo(texts).text("Chat msgs will show up here.");

    var button = $("<button/>",{
    }).addClass("chatfields").appendTo(chatWin).text("Submit").click(sendChat);

    $("body").peerbind("chat",addChat);
}

function startChat() {
    $("#chatwindow").animate({
        bottom:0
    });

    $(".chatnamefields").fadeOut();
    $(".chatfields").animate({
        opacity:1
    });

    if ( localStorage && $("#chatname").val() != null ) {
        localStorage.chatname = $("#chatname").val();
    }
}

function sendChat() {
    $("body").peertrigger("chat", [$("#chatname").val(), $("#chat").val()]);
}

function addChat(e) {
    if ( e.srcPeer ) {
        $("<div/>",{
        }).addClass("chattext").insertBefore($("#texts").children(":first")).text(e.peerData[0]+" says: "+e.peerData[1]);
    }
    else {
        $("<div/>",{
        }).addClass("chattext").insertBefore($("#texts").children(":first")).text("You said: "+e.peerData[1]);
    }

    if ($(".chattext").length ) {
        $(".chattext").each(function(i) {
            if ( i > 9 ) $(this).remove();
        });
    }
}
